import { Component, ElementRef, Input, OnInit, ViewChild } from '@angular/core';
import { IonSegment } from '@ionic/angular';
import { AppGlobalService } from 'src/app/shared/service/app-global.service';
import { EventService } from 'src/app/shared/service/event.service';
import { HttpService } from 'src/app/shared/service/http.service';
import { PageModalService } from 'src/app/shared/service/page-modal-service';
//tslint:disable

@Component({
  selector: 'app-switch-block-button',
  templateUrl: './switch-block-button.component.html',
  styleUrls: ['./switch-block-button.component.scss'],
})
export class SwitchBlockButtonComponent implements OnInit {
  @Input() tagData;
  index = 0;
  refreshFilterId: any;
  key: any;
  type = "filter";
  switchBlockButtonId = 'SwitchBlockButtonComponentID';
  @ViewChild("switchBlockSegment", { read: ElementRef }) private segment: ElementRef;
  @ViewChild('switchBlockSegment', null) ionSegment: IonSegment;
  selectedSegment = 0;
  // result: any = { showName: "", filter: {}, order: {} };
  isDefault = false;

  mainBoxCssStyle: any;
  dateFilterBoxCssStyle: any;

  // 开始时间
  startDateBoxCssStyle: any;
  startDateLabel: any;
  startDateFormKey = 'startDate';
  startDateValue: any;
  startDateValueCssStyle: any;
  startDateArrowIcon: any;
  startDateArrowIconCssStyle: any;
  startDateInnerBoxCssStyle: any;

  // 结束时间
  endDateBoxCssStyle: any;
  endDateLabel: any;
  endDateFormKey = 'endDate';
  endDateValue: any;
  endDateValueCssStyle: any;
  endDateArrowIcon: any;
  endDateArrowIconCssStyle: any;
  endDateInnerBoxCssStyle: any;

  startDate: any;
  endDate: any;

  showDateFilter = false;//是否显示日期控件

  dateListerStr = '';
  dateListerParams: any;
  commentParams: any;

  currentSegmentIndex = 0;
  segmentId = 'segmentId';
  constructor(
    private httpService: HttpService,
    private ags: AppGlobalService,
    private pageModalService: PageModalService,
    private eventService: EventService
  ) { }

  ngOnInit() {
    console.log(new Date().toLocaleString() + '.' + new Date().getMilliseconds() + ' switchBlockButton 	   ', '  	 ngOnInit  ');
    this.switchBlockButtonId += new Date().getTime();
    this.segmentId +=new Date().getTime();
    if (this.tagData && this.tagData.data.length > 0) {

      this.ags.scListTagName = this.tagData.data[0].listTagName;

      // 1.9.17 蜂喔用户新增参数联调
      if (this.tagData.data[0] && this.tagData.data[0].mainBoxCssStyle) {
        this.mainBoxCssStyle = this.tagData.data[0].mainBoxCssStyle;
      }
      // 1.6.34 蜂喔商户新增参数联调
      if (this.tagData.data[0] && this.tagData.data[0].dateFilterBoxCssStyle) {
        this.dateFilterBoxCssStyle = this.tagData.data[0].dateFilterBoxCssStyle;
      }
      // 开始时间
      if (this.tagData.data[0] && this.tagData.data[0].startDateBoxCssStyle) {
        this.startDateBoxCssStyle = this.tagData.data[0].startDateBoxCssStyle;
      }
      if (this.tagData.data[0] && this.tagData.data[0].startDateLabel) {
        this.startDateLabel = this.tagData.data[0].startDateLabel;
      }
      if (this.tagData.data[0] && this.tagData.data[0].startDateFormKey) {
        this.startDateFormKey = this.tagData.data[0].startDateFormKey;
      }
      if (this.tagData.data[0] && this.tagData.data[0].startDateValue) {
        this.startDateValue = this.tagData.data[0].startDateValue;
      }
      if (this.tagData.data[0] && this.tagData.data[0].startDateValueCssStyle) {
        this.startDateValueCssStyle = this.tagData.data[0].startDateValueCssStyle;
      }
      if (this.tagData.data[0] && this.tagData.data[0].startDateArrowIcon) {
        this.startDateArrowIcon = this.tagData.data[0].startDateArrowIcon;
      }
      if (this.tagData.data[0] && this.tagData.data[0].startDateArrowIconCssStyle) {
        this.startDateArrowIconCssStyle = this.tagData.data[0].startDateArrowIconCssStyle;
      }

      if (this.tagData.data[0] && this.tagData.data[0].startDateInnerBoxCssStyle) {
        this.startDateInnerBoxCssStyle = this.tagData.data[0].startDateInnerBoxCssStyle;
      }


      // 结束时间
      if (this.tagData.data[0] && this.tagData.data[0].endDateBoxCssStyle) {
        this.endDateBoxCssStyle = this.tagData.data[0].endDateBoxCssStyle;
      }
      if (this.tagData.data[0] && this.tagData.data[0].endDateLabel) {
        this.endDateLabel = this.tagData.data[0].endDateLabel;
      }
      if (this.tagData.data[0] && this.tagData.data[0].endDateFormKey) {
        this.endDateFormKey = this.tagData.data[0].endDateFormKey;
      }
      if (this.tagData.data[0] && this.tagData.data[0].endDateValue) {
        this.endDateValue = this.tagData.data[0].endDateValue;
      }
      if (this.tagData.data[0] && this.tagData.data[0].endDateValueCssStyle) {
        this.endDateValueCssStyle = this.tagData.data[0].endDateValueCssStyle;
      }
      if (this.tagData.data[0] && this.tagData.data[0].endDateArrowIcon) {
        this.endDateArrowIcon = this.tagData.data[0].endDateArrowIcon;
      }
      if (this.tagData.data[0] && this.tagData.data[0].endDateArrowIconCssStyle) {
        this.endDateArrowIconCssStyle = this.tagData.data[0].endDateArrowIconCssStyle;
      }
      if (this.tagData.data[0] && this.tagData.data[0].endDateInnerBoxCssStyle) {
        this.endDateInnerBoxCssStyle = this.tagData.data[0].endDateInnerBoxCssStyle;
      }


      if (this.tagData.data[0].params) {
        const paramKeys = Object.keys(this.tagData.data[0].params);
        for (let j = 0; j < paramKeys.length; j++) {
          const keyName = paramKeys[j];
          if (keyName !== 'filter') {
            const newParamObj = {};
            newParamObj[keyName] = this.tagData.data[0].params[keyName];
            Object.assign(this.ags.scResult, newParamObj);
          } else if (keyName === "filter") {
            this.ags.scResult.filter = this.tagData.data[0].params.filter;
          }
        }
      }
    }
    if (this.tagData.data) {
      for (let index = 0; index < this.tagData.data.length; index++) {
        const element = this.tagData.data[index];
        if (element.selected && element.selected === 'true') {

          this.selectedSegment = index;
          if (element.hideState === undefined) {
            if (document.getElementById('hideState')) {
              document.getElementById('hideState').style.display = 'none';
            }
          } else {
            if (document.getElementById('hideState')) {
              document.getElementById('hideState').style.display = 'block';
            }
          }
          break;
        }
      }
    }

    this.startDate = {
      data: {
        experience: {
          formType: "",
          formKey: this.endDateFormKey,
          label: "请填写",
          placeHolder: this.ags.getNowFormatDateYYYYMMDD(),
          value: this.ags.getNowFormatDateYYYYMMDD(),
          max: this.ags.getNowFormatDateYYYYMMDD(),
          min: this.ags.getNowFormatDateYYYYMMDD(1),
          mode: 'date',// month 到月份 date 到天
          rules: [
            {
              name: 'required',
              value: false,
              message: "请选择开始时间",
            }
          ],

        }
      }
    };
    this.endDate = {
      data: {
        experience: {
          formType: "",
          formKey: this.endDateFormKey,
          label: "请填写",
          placeHolder: this.ags.getNowFormatDateYYYYMMDD(),
          value: this.ags.getNowFormatDateYYYYMMDD(),
          max: this.ags.getNowFormatDateYYYYMMDD(),
          min: this.ags.getNowFormatDateYYYYMMDD(1),
          mode: 'date',// month 到月份 date 到天
          rules: [
            {
              name: 'required',
              value: false,
              message: "请选择结束时间",
            }
          ],

        }
      }
    };
  }

  // type 1 startDate, 2 endDate
  datetime(result: Date, item, type) {
    item.value = this.currentDateFormat(result, 'yyyy-mm-dd');
    item.showValue = item.showValue !== undefined ? this.ags.handleDate(result) : undefined;
    item.defValue = result;
    if (this.dateListerStr) {
      if (type === 1) {
        this.startDateValue = this.currentDateFormat(new Date(this.startDate.data.experience.value), 'yyyy-mm-dd');
        this.dateListerParams.filter[this.startDateFormKey] = this.startDateValue;
      } else if (type === 2) {
        this.endDateValue = this.currentDateFormat(new Date(this.endDate.data.experience.value), 'yyyy-mm-dd');
        this.dateListerParams.filter[this.endDateFormKey] = this.endDateValue;
      }
      this.eventService.eventEmit.emit(this.dateListerStr, this.dateListerParams);
    }
  }

  switchBlockClick(item, className, dateIndex?) {
    if (document.getElementById('hideState')) {
      document.getElementById('hideState').style.display = item.hideState === undefined ? 'none' : 'block';
    }
    this.showDateFilter = item.showDateFilter !== undefined ? true : false;
    if (this.showDateFilter) {
      item.params.filter['startDate'] = this.startDate.data.experience.value;
      item.params.filter['endDate'] = this.endDate.data.experience.value;
    } else {
      delete item.params.filter['startDate'];
      delete item.params.filter['endDate'];
    }
    // 1.9.13
    if (item && item.link) {
      this.pageModalService.openPage(item.link);
      return;
    }

    if (item.params
      && item.params.plugin_type_id !== undefined
      && item.params.filter !== undefined
      && item.params.plugin_type_id !== item.params.filter.opportunity_plugin_id) {
      item.params.filter.opportunity_plugin_id = item.params.plugin_type_id;
    }
    try {
      if (dateIndex !== undefined) {
        this.tagData.data[dateIndex].selected = 'true';
      }
      item.selected = 'true';
      const nameId = 'home-switch-box-button-' + className + this.index;
      const array = this.tagData.data;//2024.06.25   document.getElementsByClassName(nameId);
      const divArray = document.getElementsByClassName('slider-Div');
      for (let index = 0; index < array.length; index++) {
        const element = array[index];
        const domEle = document.getElementById(element.id);
        const divEle = divArray[index];
        if (item.id === element.id) {

          // item.check = 1;
          this.addClass(domEle, "switch-checked-" + className);
          if (divEle !== undefined) {
            this.removeClass(divEle, "sliderbox1");
            this.addClass(divEle, "sliderbox");
          }

          this.addClass(domEle.children[0], "home-checked-font-" + className);
          if (item.params) {
            const paramKeys = Object.keys(item.params);
            for (let j = 0; j < paramKeys.length; j++) {
              const keyName = paramKeys[j];
              if (keyName !== 'filter') {
                const newParamObj = {};
                newParamObj[keyName] = item.params[keyName];
                Object.assign(this.ags.scResult, newParamObj);
              } else if (keyName === "filter") {
                this.ags.scResult.filter = item.params.filter;
              }
            }
          }
          if (item.listTagName && item.commonFilterId) {
            this.requestData(item, className);
          } else {
            const emitStr = item.listTagName + 'AskForList';
            if (item.params === undefined) {
              item.params = { content: {} };
            }
            if (this.showDateFilter && item.isSubmit === undefined) {
              this.dateListerStr = emitStr;
              this.dateListerParams = item.params;
              return;
            } else if (this.showDateFilter && item.isSubmit === '1') {
              this.dateListerStr = emitStr;
              this.dateListerParams = item.params;
            }
            localStorage.setItem(emitStr + 'Tag', '1');
            this.eventService.eventEmit.emit(emitStr, item.params);
          }
        } else {
          this.tagData.data[index].selected = 'false';
          // item.check = 0;
          this.removeClass(domEle, "switch-checked-" + className);
          this.removeClass(domEle.children[0], "home-checked-font-" + className);
          if (divEle !== undefined) {
            this.removeClass(divEle, "sliderbox");
            this.addClass(divEle, "sliderbox1");
          }
        }
      }

    } catch (error) {

    }
  }

  requestData(item, className?) {
    try {
      if (this.showDateFilter) {
        return;
      }
      if (className !== undefined && className === 'threeCss' || className === 'fourthCss') {
        const emitStr = item.listTagName + 'AskForList';
        if (item.params === undefined) {
          item.params = { content: {} };
        }
        localStorage.setItem(emitStr + 'Tag', '1');
        this.eventService.eventEmit.emit(emitStr, item.params);
      } else {
        if (item.commonFilterId && item.commonFilterId === 'empty') {
          this.key = Object.keys(item.params)[0];
          this.getResult({ active: true, displayName: '', value: item.params[Object.keys(item.params)[0]] }, {}, item.listTagName);
        } else if(item.commonFilterId && (item.commonFilterId.indexOf('homeFilterId') > -1 || item.commonFilterId.indexOf('hommeFilterId') > -1)){
          const emitStr = item.listTagName + 'AskForList';
          if (item.params === undefined) {
            item.params = { content: {} };
          }
          localStorage.setItem(emitStr + 'Tag', '1');
          this.eventService.eventEmit.emit(emitStr, item.params);
        } else {
          const params = {
            content: item.params,
            id: item.commonFilterId,
            sessionId: localStorage.getItem('sessionId')
          };
          this.httpService.post("application/submit", params, res => {
            if (res && res.data) {
              let filterItems;
              let filterTag;
              if (res.data.filterItems) {
                filterItems = JSON.parse(res.data.filterItems);
                filterTag = { filterItems };
                if (filterItems) {
                  setTimeout(() => {
                    localStorage.setItem('updateCommonFilterTag', '1');
                    this.eventService.eventEmit.emit('updateCommonFilter', filterTag);
                  }, 5);
                }
              }
              this.getResult({ active: true, displayName: '', value: this.ags.scResult.filter[this.key] }, filterTag, item.listTagName);
            }
          }, err => {
            console.log('error----->' + JSON.stringify(err));
          });
        }

      }
    } catch (error) {
    }
  }

  addClass(ele, value) {
    if (value) {
      let curValue = this.getClass(ele);
      if (curValue.indexOf(value) === -1) {
        curValue = curValue + " " + value;
      }
      ele.setAttribute("class", curValue.trim());
    }
  }
  getClass(elem) {
    return elem.getAttribute && elem.getAttribute("class") || "";
  }
  removeClass(ele, value) {
    if (value) {
      let curValue = this.getClass(ele);
      if (curValue.indexOf(value) > -1) {
        curValue = (" " + curValue + " ").replace(" " + value + " ", " ");
      }
      ele.setAttribute("class", curValue.trim());
    }
  }
  hasClass(ele, value) {
    let has = false;
    if (value) {
      const curValue = this.getClass(ele);
      if (curValue.indexOf(value) > -1) {
        has = true;
      }
    }
    return has;
  }
  getResult(obj, commonFilterTag, listTagName) {
    const pos = JSON.parse(localStorage.getItem("position"));
    let tempShowName = sessionStorage.getItem('showName');
    if (commonFilterTag && commonFilterTag.keyTag) {
      tempShowName = commonFilterTag.keyTag;
    }
    this.ags.scResult.showName = tempShowName;
    const kFilter = "filter";
    const kType = "filter";
    const kOrder = "order";
    const kLocation = "location";
    const kStrSort = "sort";
    if (this.type === "filter") {
      if (obj.min !== undefined || obj.max !== undefined) {
        (obj.min === undefined || obj.min === null) ? obj.min = "0" : obj.min = obj.min;
        // 用户输入了最小值如果手动删除最大值已与产品沟通传空串
        this.ags.scResult[kFilter][this.key] = obj.min + "," + (obj.max === undefined ? "" : obj.max === null ? "" : obj.max);
      } else {
        this.ags.scResult[kFilter][this.key] = obj.value;
      }
    } else if (this.type === kOrder) {
      if (this.ags.scResult[kLocation]) {
        delete this.ags.scResult[kLocation];
      }
      const kSort = {};
      if (obj.value !== undefined) {
        obj.value.forEach(v => {
          kSort[v.field] = v.value;
        });
        this.ags.scResult[kOrder][kStrSort] = kSort;
      }
    }
    Object.keys(this.ags.scResult).forEach(element => {
      if (element !== 'order') {
        if (this.ags.scResult[element] === null) { delete this.ags.scResult[element]; }
      }
    });
    setTimeout(() => {
      localStorage.setItem(listTagName + 'AskForListTag', listTagName);
      this.eventService.eventEmit.emit(listTagName + 'AskForList', this.ags.scResult);
    }, 20);
  }


  switchSegment(item,divId,j){
    if(divId){      
      if(document.getElementById(divId)){
        const array = document.getElementById(divId);
        if(array&&array.children.length>0){
          for (let index = 0; index < array.children.length; index++) {
            const element = array.children[index];
            this.removeClass(element, "checkedSegmentBtn");
            this.addClass(element,'normalSegmentBtn');
          }
          this.removeClass(array.children[j], "normalSegmentBtn");
          this.addClass(array.children[j],'checkedSegmentBtn'); 
          const listTagName = this.tagData.data[0].listTagName;
          localStorage.setItem(listTagName + 'AskForListTag', listTagName);
          this.eventService.eventEmit.emit(listTagName + 'AskForList', this.tagData.data[j].params);
          this.commentParams = this.tagData.data[j].params;
        }
      }      
    }
  }


  async segmentChanged(e: any, indexTab?) {
    let index = 0;
    if (indexTab !== undefined) {
      index = indexTab;
    } else {
      if (e.detail.value === 'NaN') { return; }
      index = e.detail.value;
    }
    this.currentSegmentIndex = index - 0;
    try {
      const segmentButton = this.segment.nativeElement.children[index];
      segmentButton.scrollIntoView({
        behavior: 'smooth',
        inline: 'center',
        block: 'nearest'
      });
    } catch (error) {
    }
    const listTagName = this.tagData.data[0].listTagName;
    localStorage.setItem(listTagName + 'AskForListTag', listTagName);
    this.eventService.eventEmit.emit(listTagName + 'AskForList', this.tagData.data[index].params);
    this.commentParams = this.tagData.data[index].params;
  }

  sort(o) {
    const listTagName = this.tagData.data[0].listTagName;
    this.isDefault = !this.isDefault;
    localStorage.setItem(listTagName + 'AskForListTag', listTagName);
    let params = o;
    if (this.commentParams && this.commentParams !== undefined) {
      Object.assign(params, this.commentParams);
    }
    this.eventService.eventEmit.emit(listTagName + 'AskForList', params);
  }

  formatIt(date: Date, form: string) {
    const pad = (n: number) => (n < 10 ? `0${n}` : n);
    const dateStr = `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
    const timeStr = `${pad(date.getHours())}:${pad(date.getMinutes())}`;
    if (form === 'YYYY-MM-DD') {
      return dateStr;
    }
    if (form === 'HH:mm') {
      return timeStr;
    }
    return `${dateStr} ${timeStr}`;
  }
  getDateTime(date?) {
    if (!date) {
      return new Date();
    }
    if (date.indexOf(' ') > -1) {
      // console.log(new Date(Date.parse(date.replace(/-/g, "/"))));
      return new Date(Date.parse(date.replace(/-/g, "/")));
    } else {
      // console.log(new Date(Date.parse((date + ' ' + '23:59:59').replace(/-/g, "/"))));
      return new Date(Date.parse((date + ' ' + '23:59:59').replace(/-/g, "/")));
    }
  }
  currentValue(item) {
    if (!item.value || item.value === '') {
      return item.placeHolder;
    } else {
      return item.value;
    }
  }
  // 时间段选择
  currentDateFormat(date, format: string = 'HH:MM'): any {
    const pad = (n: number): string => (n < 10 ? `0${n}` : n.toString());
    return format
      .replace('yyyy', date.getFullYear())
      .replace('mm', pad(date.getMonth() + 1))
      .replace('dd', pad(date.getDate()))
      .replace('HH', pad(date.getHours()))
      .replace('MM', pad(date.getMinutes()))
      .replace('ss', pad(date.getSeconds()));
  }

  getDate(max, item) {
    if (item.max === max) {
      return item.maxDate = item.maxDate ? item.maxDate : this.getDateTime(max);
    } else if (item.min === max) {
      return item.minDate = item.mimDate ? item.minDate : this.getDateTime(max);
    }
  }
  ngOnDestroy(): void {
    this.eventService.removeCustomListListeners();
  }
}
